package runInfo;

import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;

public class NewThreadExample {

	private Shell sShell = null;

	private static class TimeLoop implements Runnable{
		public void run(){
			long patience = 1000*10; 
			long startTime = System.currentTimeMillis();
			long currentTime = System.currentTimeMillis();
			while((currentTime-startTime<=patience)){
				currentTime = System.currentTimeMillis();
				System.out.println("we've been waiting for: " + ((currentTime-startTime)/1000.0)+ " s");
				double rNum = Math.random()*1000.0;
				try{
					Thread.sleep((long) 1000);
				}catch(InterruptedException e){
					threadMessage("Not waiting anymore!");
				}
			}
		}
	}
	
	static void threadMessage(String message){
		String threadName = Thread.currentThread().getName();
		System.out.format("%s: %s%n",threadName,message);
	}
	
	private void createSShell() {
		sShell = new Shell();
		sShell.setText("Shell");
		sShell.setSize(new Point(300, 200));
		sShell.setLayout(new GridLayout());
	}
	private static class MessageLoop implements Runnable{
		public void run(){
			String importantInfo[] = {
					"Mares eat oats",
					"Does eat oats",
					"Little lambs eat ivy",
					"a kid will eat ivy too"
			};
			try{
				for(int i=0; i < importantInfo.length; i++){
					double rNum = Math.random()*4000.0;
					Thread.sleep((long)rNum);
					threadMessage(importantInfo[i]);
				}
			}catch(InterruptedException e){
				threadMessage("I wasn't done!");
			}
		}
	}
	
	public static void main(String args[]) throws InterruptedException{
		long patience = 1000*10;
		
		
		if(args.length >0){
			try{
				patience = Long.parseLong(args[0])*1000;
			} catch(NumberFormatException e){
				System.err.println("Argument must be an integer.");
				System.exit(1);
			}
		}
		threadMessage("Starting MessageLoop Thread");
		long startTime = System.currentTimeMillis();
		Thread t = new Thread(new MessageLoop());
		t.start();
		
		threadMessage("Starting third thread to count the time");
		Thread t2 = new Thread(new TimeLoop());
		t2.start();
		
		threadMessage("Waiting for MessageLoop thread to finish");
		while(t.isAlive()){
			threadMessage("Still waiting...");
			//wait max of 1 sec for messageloop thread to finish
			t.join(1000);
			if(((System.currentTimeMillis()-startTime) > patience) && t.isAlive()){
				threadMessage("Tired of waiting!");
				t.interrupt();
				//shouldn't be long now - wait indefinitely
				t.join();
				
			}
		}
		t2.stop();
//		t2.interrupt();
//		t2.join();
		threadMessage("Finally!");
	}

}
